import os
from fastapi import FastAPI
from dotenv import load_dotenv
from tortoise.contrib.fastapi import register_tortoise
from . import settings
from .apps.common.views import app as common_app
from .apps.users.views import app as user_app
from .utils import middleware, exceptions, redis_tools


def create_app() -> FastAPI:
    """
    创建App应用对象的工厂函数
    App的初始化代码放在这里
    :return:
    """
    # 读取api服务端的.env文件[.env必须保存在main.py文件的同级目录下]
    load_dotenv()

    app: FastAPI = FastAPI(
        title=os.environ.get('APP_NAME', 'FastAPI'),
        version=os.environ.get('APP_VERSION', '0.0.1'),
        summary=os.environ.get('APP_SUMMARY', 'FastAPI'),
        description=os.environ.get('APP_DESCRIPTION', 'FastAPI'),
        # 把全局异常函数注册到App应用对象中
        exception_handlers={
            exceptions.HTTPException: exceptions.global_http_exception_handler,
            exceptions.RequestValidationError: exceptions.global_validation_exception_handler,
        }
    )

    # 把Tortoise-orm注册到App应用对象中
    register_tortoise(
        app,
        config=settings.TORTOISE_ORM,
        add_exception_handlers=True,  # 是否启用自动异常处理
    )

    # 把Redis注册到App应用对象中
    redis_tools.register_redis(
        app,
        config=settings.REDIS
    )

    # 注册所有的分组应用对象到App应用对象
    app.include_router(common_app, prefix='') # 公共数据应用
    app.include_router(user_app, prefix='/users')  # 用户数据应用
    # 注册中间件函数
    http_middleware = app.middleware('http')
    http_middleware(middleware.log_requests)

    return app